package com.mes.biz.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mes.biz.domain.BizOrder;
import com.mes.biz.domain.BizOrderAttach;
import com.mes.biz.domain.BizOrderInstaller;
import com.mes.biz.domain.vo.OrderDeliveryVo;
import com.mes.biz.domain.vo.OrderInstallVo;
import com.mes.biz.mapper.BizOrderInstallerMapper;
import com.mes.biz.service.BizOrderAttachService;
import com.mes.biz.service.BizOrderInstallerService;
import com.mes.biz.service.BizOrderService;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.page.PageDomain;
import com.mes.common.core.service.BaseServiceImpl;
import com.mes.common.exception.BizException;
import com.mes.common.utils.SecurityUtils;
import com.mes.common.utils.StringUtils;
import com.mes.common.utils.sql.SqlUtil;
import org.apache.commons.compress.utils.Sets;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 销售单安装人员Service业务层处理
 * @author hwg
 * @email hwg
 * @date 2023-05-15
 */
@Service
@Transactional(readOnly = true)
public class BizOrderInstallerServiceImpl extends BaseServiceImpl<BizOrderInstallerMapper, BizOrderInstaller> implements BizOrderInstallerService {

    @Resource
    private BizOrderInstallerMapper bizOrderInstallerMapper;
    @Resource
    private BizOrderService bizOrderService;
    @Resource
    private BizOrderAttachService bizOrderAttachService;

    /**
     * 获取单条数据
     * @param bizOrderInstaller 销售单安装人员
     * @return 销售单安装人员
     */
    @Override
    public BizOrderInstaller get(BizOrderInstaller bizOrderInstaller) {
        BizOrderInstaller dto = super.get(bizOrderInstaller);
        return dto;
    }

    /**
     * 获取单条数据
     * @param id 销售单安装人员id
     * @return 销售单安装人员
     */
    @Override
    public BizOrderInstaller get(String id) {
        BizOrderInstaller dto = super.get(id);
        return dto;
    }

    /**
     * 查询销售单安装人员列表
     * @param bizOrderInstaller 销售单安装人员
     * @return 销售单安装人员
     */
    @Override
    public List<BizOrderInstaller> findList(BizOrderInstaller bizOrderInstaller) {
		List<BizOrderInstaller> bizOrderInstallerList = super.findList(bizOrderInstaller);
        return bizOrderInstallerList;
    }

    /**
     * 分页查询销售单安装人员列表
     * @param bizOrderInstaller 销售单安装人员
     * @return 销售单安装人员
     */
    @Override
    public PageInfo<BizOrderInstaller> findPage(BizOrderInstaller bizOrderInstaller) {
		PageInfo<BizOrderInstaller> page = super.findPage(bizOrderInstaller);
        return page;
    }

    /**
     * 保存销售单安装人员
     * @param bizOrderInstaller
     * @return 结果
     */
    @Override
    public boolean save(BizOrderInstaller bizOrderInstaller) {
        return super.save(bizOrderInstaller);
    }

    /**
     * 删除销售单安装人员信息
     * @param bizOrderInstaller
     * @return 结果
     */
    @Override
    public boolean remove(BizOrderInstaller bizOrderInstaller) {
        return super.remove(bizOrderInstaller);
    }

    /**
     * 批量删除销售单安装人员
     * @param ids 需要删除的销售单安装人员ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteBizOrderInstallerByIds(String[] ids) {
        return mapper.deleteBizOrderInstallerByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    public List<BizOrderInstaller> getBizOrderInstallerByOrderId(String orderId,String installerType) {
        return bizOrderInstallerMapper.getBizOrderInstallerByOrderId(orderId,installerType);
    }

    @Override
    public boolean getInstallerByOrderId(String orderId, String installerType) {
        boolean flag=true;
        List<BizOrderInstaller> list = bizOrderInstallerMapper.getBizOrderInstallerByOrderId(orderId, installerType);
        if (list != null && list.size()>0){
            for (BizOrderInstaller bizOrderInstaller :list){
                if (!"2".equals(bizOrderInstaller.getInstallerStatus())) {
                    flag = false;
                    break;
                }
            }
        }else {
            flag=false;
        }
        return flag;
    }

    @Transactional(readOnly = false)
    @Override
    public boolean updateStatus(BizOrderInstaller bizOrderInstaller1) {
        BizOrderInstaller bizOrderInstaller = get(bizOrderInstaller1.getId());
        bizOrderInstaller.setInstallerStatus(bizOrderInstaller1.getInstallerStatus());
        String orderId = bizOrderInstaller.getOrderId();
        boolean save = super.save(bizOrderInstaller);
        if (save){
            if ("2".equals(bizOrderInstaller.getInstallerStatus())){
                BizOrder bizOrder = bizOrderService.get(orderId);
                boolean flag = getInstallerByOrderId(orderId, bizOrderInstaller.getInstallerType());
                if (flag){
                    if ("1".equals(bizOrderInstaller.getInstallerType())){
                        if (StringUtils.isNotEmpty(bizOrder.getInstallType()) &&"1".equals(bizOrder.getInstallType())){
                            bizOrder.setOrderStatus("9");
                        }
                        bizOrder.setShippingStatus("1");
                    }else if ("2".equals(bizOrderInstaller.getInstallerType())){
                        if (!BaseEntity.IS_HAHDLE.equals(bizOrder.getShippingStatus())){
                            throw new BizException("仓库未发货，请联系派单员");
                        }
                        bizOrder.setOrderStatus("9");
//                        bizOrder.setInstallDate(new Date());
                    }
                    bizOrderService.save(bizOrder);
                }
                if ("2".equals(bizOrderInstaller.getInstallerType())){
                    List<BizOrderAttach> attachList = bizOrderInstaller1.getAttachList();
                    String tenantId = SecurityUtils.getTenantId();
                    for (BizOrderAttach attach:attachList) {
                        BizOrderAttach orderAttach = new BizOrderAttach();
                        orderAttach.setTenantId(tenantId);
                        orderAttach.setOrderId(orderId);
                        orderAttach.setAttachPath(attach.getAttachPath());
                        orderAttach.setType(4);
                        bizOrderAttachService.save(orderAttach);
                    }
                }
            }
        }
        return true;
    }

    @Transactional(readOnly = false)
    @Override
    public boolean saveBatch(BizOrder bizOrder) {
        //删除人员
        String orderId =bizOrder.getId();
        List<BizOrderInstaller> bizOrderInstallerList = mapper.getBizOrderInstallerByOrderId(orderId,null);
        Set<String> productExistsSets = Sets.newHashSet();
        if (bizOrderInstallerList !=null && bizOrderInstallerList.size()>0){
            bizOrderInstallerList.forEach(existsVO -> {
                productExistsSets.add(existsVO.getId());
            });
        }
        List<BizOrderInstaller> bizOrderInstallers = bizOrder.getBizOrderInstallers();
        Date date=null;
        if (bizOrderInstallers.size() > 0){
            for (BizOrderInstaller installer : bizOrderInstallers){
                if ("2".equals(installer.getInstallerType())){
                    if (date != null){
                        if (installer.getInstallDate()!=null){
                            long time = date.getTime();
                            long installDate = installer.getInstallDate().getTime();
                            if (time > installDate){
                                date=installer.getInstallDate();
                            }
                        }
                    }else {
                        date=installer.getInstallDate();
                    }
                }
                installer.setTenantId(SecurityUtils.getTenantId());
                productExistsSets.remove(installer.getId());
                super.save(installer);
            }
        }
        if (productExistsSets.size()>0){
            String[] ids = productExistsSets.toArray(new String[0]);
            deleteBizOrderInstallerByIds(ids);
        }
        BizOrder bizOrder1 = bizOrderService.get(orderId);
        if (date != null){
            bizOrder1.setInstallDate(date);
        }
        if ("6".equals(bizOrder1.getOrderStatus())) {
            bizOrder1.setOrderStatus("7");
        }

        if ("7".equals(bizOrder1.getOrderStatus())) {
            boolean deliveryFlag = getInstallerByOrderId(orderId, "1");
            if (deliveryFlag){
                bizOrder1.setShippingStatus("1");
                boolean installFlag = getInstallerByOrderId(orderId, "2");
                if (installFlag){
                    bizOrder1.setOrderStatus("9");
                }
            }
        }

        bizOrderService.save(bizOrder1);
        return true;
    }

    @Override
    public List<BizOrderInstaller> getInstallNameByOrderId(String orderId) {
        return bizOrderInstallerMapper.getInstallNameByOrderId(orderId);
    }
    @Override
    public PageInfo<OrderDeliveryVo> listDeliveryStatPage(BizOrderInstaller bizOrderInstaller) {
        PageDomain page = bizOrderInstaller.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        bizOrderInstaller.setTenantId(SecurityUtils.getTenantId());
        return new PageInfo(bizOrderInstallerMapper.listDeliveryStat(bizOrderInstaller));
    }

    @Override
    public List<OrderDeliveryVo> listDeliveryStat(BizOrderInstaller bizOrderInstaller) {
        bizOrderInstaller.setTenantId(SecurityUtils.getTenantId());
        return bizOrderInstallerMapper.listDeliveryStat(bizOrderInstaller);
    }

    @Override
    public PageInfo<OrderInstallVo> listInstallStatPage(BizOrderInstaller bizOrderInstaller) {
        PageDomain page = bizOrderInstaller.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        bizOrderInstaller.setTenantId(SecurityUtils.getTenantId());
        return new PageInfo(bizOrderInstallerMapper.listInstallStat(bizOrderInstaller));
    }

    @Override
    public List<OrderInstallVo> listInstallStat(BizOrderInstaller bizOrderInstaller) {
        bizOrderInstaller.setTenantId(SecurityUtils.getTenantId());
        return bizOrderInstallerMapper.listInstallStat(bizOrderInstaller);
    }

}
